package com.adjaisd.scarecrow.common.utils.mqtt;

import com.adjaisd.scarecrow.common.config.MqttConfig;
import com.adjaisd.scarecrow.common.utils.jwt.JwtUtils;
import com.adjaisd.scarecrow.service.RedisService;
import lombok.extern.slf4j.Slf4j;
import org.eclipse.paho.client.mqttv3.*;

import java.util.HashMap;
import java.util.Map;

@Slf4j
public class MqttUtils {

    public static Map<String, String> getToken(MqttConfig mqttConfig, RedisService redisService) {
        HashMap<String, String> map = new HashMap<>();
        String key = "token" + mqttConfig.getClientId();
        String jwtToken = JwtUtils.getJwtToken(mqttConfig.getClientId(), mqttConfig.getUsername(), mqttConfig.getPassword(), mqttConfig.getSalt());
        redisService.set(key, jwtToken, 60);
        map.put("username", mqttConfig.getUsername());
        map.put("password", jwtToken);
        return map;
    }

    public static MqttClient connect(String brokerUrl, String clientId,
                                     String username, String password,
                                     MqttCallback callback) {
        System.out.println("MqttUtils连接emq");
        try {
            MqttClient mqttClient = new MqttClient(brokerUrl, clientId);
            mqttClient.setCallback(callback);
            MqttConnectOptions options = new MqttConnectOptions();
            options.setUserName(username);
            options.setPassword(password.toCharArray());
            options.setMaxInflight(1000);
            options.setCleanSession(false);
            options.setKeepAliveInterval(20);

            mqttClient.connect(options);
            return mqttClient;
        } catch (MqttException e) {
            e.printStackTrace();
            return null;
        }
    }

    public static void publish(MqttClient mqttClient, String topic, String msg, int qos) {
        try {
            MqttMessage message = new MqttMessage();
            message.setQos(qos);
            message.setPayload(msg.getBytes());
            MqttTopic mTopic = mqttClient.getTopic(topic);
            if (null == mTopic) {
                log.error("topic not exist");
                return;
            }
            MqttDeliveryToken token = mTopic.publish(message);
            token.waitForCompletion();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void subscribe(MqttClient mqttClient, String topicName) throws MqttException {
        mqttClient.subscribe(topicName);
    }

    public static void unsubscribe(MqttClient mqttClient, String topicName) throws MqttException {
        mqttClient.unsubscribe(topicName);
    }
}
